<template>
  <el-dialog :title="title" :visible.sync="visible" width="1000px" :close-on-click-modal="false"
    :close-on-press-escape="false" v-loading="addOrUpdateloading">
    <div>
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-row>
          <el-form-item label="单词" prop="word">
            <el-input v-model="form.word" placeholder="请输入单词" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="标签" prop="tag">
            <el-tag :key="tag" v-for="tag in form.tag" closable :disable-transitions="false" @close="handleClose(tag)">
              {{tag}}
            </el-tag>
            <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
              @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
            </el-input>
            <el-button v-else size="small" :style="{ 'margin-left': form.tag.length > 0 ? '4px' : '0' }"
              class="button-new-tag" @click="openSelectTag" icon="el-icon-plus">添加标签</el-button>
          </el-form-item>
        </el-row>
        <el-row v-for="item in itemArray" :key="item.key">
          <el-card shadow="always" class="item">
            <div slot="header" class="clearfix">
              <span>{{item.text}}-配置</span>
              <i style="float: right; padding: 3px 0;cursor: pointer;" class="el-icon-close"
                @click="handleRemoveAttr(item)"></i>
            </div>
            <el-col :span="6" v-for="formInput in item.inputArray" :key="formInput.key">
              <el-form-item :label="formInput.text" :prop="formInput.name">
                <el-input v-model="form[formInput.name]" :placeholder="'请输入'+formInput.text" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="图片" prop="uploadImage">
                <el-upload multiple :auto-upload="false" action="" :file-list="filteredUploadImage(item.code)"
                  :on-change="(file, fileList) => handleChange(file, fileList, item.code)" accept="image/*"
                  list-type="picture-card" :on-remove="(file, fileList) => handleDeleteFile(file, item.code)">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-card>
        </el-row>
        <el-row>
          <el-form-item label="">
            <el-dropdown trigger="click">
              <el-button size="small" type="button" icon="el-icon-plus">添加词性</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item icon="el-icon-circle-check"
                  @click.native="addWordAttr('Noun','名词')">名词</el-dropdown-item>
                <el-dropdown-item icon="el-icon-circle-check"
                  @click.native="addWordAttr('Verb','动词')">动词</el-dropdown-item>
                <el-dropdown-item icon="el-icon-circle-check"
                  @click.native="addWordAttr('Adjective','形容词')">形容词</el-dropdown-item>
                <el-dropdown-item icon="el-icon-circle-check"
                  @click.native="addWordAttr('Adverb','副词')">副词</el-dropdown-item>
                <el-dropdown-item icon="el-icon-circle-check"
                  @click.native="addWordAttr('Pronoun','代词')">代词</el-dropdown-item>
                <el-dropdown-item icon="el-icon-circle-check"
                  @click.native="addWordAttr('Numeral','数词')">数词</el-dropdown-item>
                <el-dropdown-item icon="el-icon-circle-check"
                  @click.native="addWordAttr('Article','冠词')">冠词</el-dropdown-item>
                <el-dropdown-item icon="el-icon-circle-check"
                  @click.native="addWordAttr('Preposition','介词')">介词</el-dropdown-item>
                <el-dropdown-item icon="el-icon-circle-check"
                  @click.native="addWordAttr('Conjunction','连词')">连词</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="发音" prop="audioFileList">
            <el-upload multiple :auto-upload="false" action="" :on-change="handleAudioChange" accept="audio/*"
              :show-file-list="false">
              <el-button size="small" type="primary">点击选择文件</el-button>
            </el-upload>
          </el-form-item>

          <el-table :data="form.audioFileList">
            <el-table-column label="音频" align="center" width="400px" prop="url">
              <template slot-scope="scope">
                <audio :key="'audio_'+scope.row.id+'_'+scope.row.oldFileName" :src="scope.row.url" controls
                  preload="metadata">
                  您的浏览器不支持 audio 元素。
                </audio>
              </template>
            </el-table-column>
            <el-table-column label="顺序" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sortNum" placeholder="请输入顺序" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete"
                  @click="handleDeleteAudioFile(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <div style="text-align: center;">
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            {{ submitLoading ? '提交中...' : '确定' }}</el-button>
          <el-button @click="visible = false">关 闭</el-button>
        </div>
      </el-form>
      <!-- 选择等级 -->
      <SelectTag ref="selectTag" :open="tagFlag" @selected-data="selectedTagData"
        @close-select-window="closeSelectTag" />
    </div>
  </el-dialog>
</template>

<script>
  import {
    mapState
  } from 'vuex';
  import store from "@/store";

  import {
    allSaveWords,
    getWords
  } from "@/api/bus_web/thesaurus/words";
  import SelectTag from '../tag/select.vue';
  import {
    isEmpty
  } from "@/utils/validate"
  export default {
    name: "InputWordAttr",
    components: {
      SelectTag
    },
    data() {
      return {
        visible: false,
        submitLoading: false,
        title: '',
        tagFlag: false,
        //动态词性数组
        itemArray: [],
        inputVisible: false,
        inputValue: '',
        tableKey: 0,
        addOrUpdateloading: true,
        openVisiable: false,
        form: {
          word: null,
          //图片集合
          uploadImage: [],
          //单词标签
          tag: [],
          //发音文件
          audioFileList: [],
          id: null,
          complexNumber: null,
          adjectiveComparative: null,
          adjectiveSuperlative: null,
          adverbComparative: null,
          adverbSuperlative: null,
          pastParticiple: null,
          presentParticiple: null,
          thirdPersonSingular: null,
          nominative: null,
          accusative: null,
          cardinalNumber: null,
          ordinalNumber: null,
        },
        rules: {
          word: [{
            required: true,
            message: "单词不能为空",
            trigger: "blur"
          }]
        },
      };
    },
    computed: {
      filteredUploadImage() {
        return (code) => {
          return this.form.uploadImage.filter(item => item.typeCode === code);
        };
      },
      ...mapState({
        tag: state => state.selectTag.tag,
        tagSelectModel: state => state.selectTag.tagSelectModel
      })
    },
    created() {
      //      this.init()
    },
    methods: {
      reset() {
        this.itemArray = []
        this.addOrUpdateloading = true
        this.resetForm("form")
        this.form = {
          word: null,
          //图片集合
          uploadImage: [],
          //单词标签
          tag: [],
          //发音文件
          audioFileList: [],
          id: null,
          complexNumber: null,
          adjectiveComparative: null,
          adjectiveSuperlative: null,
          adverbComparative: null,
          adverbSuperlative: null,
          pastParticiple: null,
          presentParticiple: null,
          thirdPersonSingular: null,
          nominative: null,
          accusative: null,
          cardinalNumber: null,
          ordinalNumber: null,
        }
        this.visible = false
        this.title = ''
        this.tagFlag = false
        this.inputVisible = false
        this.inputValue = ''
        this.tableKey = 0
        this.openVisiable = false
      },
      //选择等级
      openSelectTag(selectVal) {
        this.tagFlag = true
        // selectVal =1 查询模式 =2 创建、修改模式
        this.$store.dispatch('selectTag/cleanTag')
        this.$store.dispatch('selectTag/setTagSelectModel', selectVal)
      },
      closeSelectTag() {
        this.tagFlag = false
      },
      //确定等级
      selectedTagData() {
        this.closeSelectTag()
        this.form.tag = [...new Set([...this.form.tag, ...this.tag.map(item => item.tagName)])]
        this.$store.dispatch('selectTag/cleanTag')
      },
      //初始化数据
      init(id) {
        this.reset()
        this.visible = true
        this.addOrUpdateloading = true
        this.$nextTick(() => {
          this.title = '新增单词配置'
          if (!isEmpty(id) && id > 0) {
            this.title = '修改单词配置'
            //  加载
            getWords(id).then(rsp => {
              let data = rsp.data
              //关联词性
              let speechList = data.speechList
              //图片列表
              let uploadWordFileParams = data.uploadWordFileParams
              //删除多余属性
              delete data.speechList
              delete data.uploadWordFileParams
              this.form = data
              this.form.uploadImage = []
              for (var i in speechList) {
                let item = speechList[i]
                this.addWordAttr(item.code, item.text)
              }
              for (var i in uploadWordFileParams) {
                let file = uploadWordFileParams[i]
                file.typeCode = file.extendKey
                file.uid = file.id
                this.form.uploadImage.push(file)
              }

              this.addOrUpdateloading = false
            })
          } else {
            this.addOrUpdateloading = false
          }
        })
      },
      //删除标签
      handleClose(tag) {
        this.form.tag.splice(this.form.tag.indexOf(tag), 1);
      },
      //标签输入
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      //标签输入确认
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.form.tag.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      //上传处理图片
      handleChange(file, fileList, code) {
        file.typeCode = code;
        const newFile = {
          ...file
        }
        this.form.uploadImage.push(newFile)
        this.tableKey++
      },
      //删除文件
      handleDeleteFile(row, code) {
        const index = this.form.uploadImage.findIndex(
          item => item.uid === row.uid && item.typeCode === code
        );
        if (index > -1) {
          const targetFile = this.form.uploadImage[index]
          if (targetFile.url?.startsWith('blob:')) {
            URL.revokeObjectURL(targetFile.url)
          }
          this.$delete(this.form.uploadImage, index)
          this.tableKey++
        }
      },
      //上传音频
      handleAudioChange(file, fileList) {
        const newFile = {
          ...file
        }
        this.form.audioFileList.push(newFile)
        this.form.audioFileList = this.form.audioFileList.map((item, index) => {
          return {
            ...item,
            sortNum: index,
            url: isEmpty(item.url) ? URL.createObjectURL(item.raw) : item.url
          };
        })
      },
      //删除音频
      handleDeleteAudioFile(row) {
        const index = this.form.audioFileList.findIndex(
          item => item.uid === row.uid
        );

        if (index > -1) {
          const targetFile = this.form.audioFileList[index]
          if (targetFile.url?.startsWith('blob:')) {
            URL.revokeObjectURL(targetFile.url)
          }
          this.$delete(this.form.audioFileList, index)
          this.tableKey++
        }
      },
      //添加词性
      addWordAttr(code, text) {
        const exists = this.itemArray.some(item => item.code === code);
        if (exists) {
          this.$modal.msgError("已经存在该词性配置");
          return
        }
        let obj = {};
        obj.code = code
        obj.text = text
        obj.key = 'code_' + code
        if (code == 'Noun') {
          //名词

          obj.inputArray = [{
            name: 'complexNumber',
            text: '复数',
            key: Math.random()
          }];
        } else if (code == 'Verb') {
          //动词
          obj.inputArray = [{
            name: 'pastParticiple',
            text: '过去分词'
          }, {
            name: 'presentParticiple',
            text: '现在分词'
          }, {
            name: 'thirdPersonSingular',
            text: '第三人称单数'
          }];
        } else if (code == 'Pronoun') {
          //代词
          obj.inputArray = [{
            name: 'nominative',
            text: '主格'
          }, {
            name: 'accusative',
            text: '宾格'
          }];
        } else if (code == 'Numeral') {
          //数词
          obj.inputArray = [{
            name: 'cardinalNumber',
            text: '基数词'
          }, {
            name: 'ordinalNumber',
            text: '序数词'
          }];
        } else if (code == 'Adverb') {
          //副词
          obj.inputArray = [{
            name: 'adverbComparative',
            text: '比较级'
          }, {
            name: 'adverbSuperlative',
            text: '宾格'
          }];
        } else if (code == 'Adjective') {
          //形容词
          obj.inputArray = [{
            name: 'adjectiveComparative',
            text: '比较级'
          }, {
            name: 'adjectiveSuperlative',
            text: '最高级'
          }];
        }
        for (var i in obj.inputArray) {
          obj.inputArray[i].key = 'input_' + obj.inputArray[i].name
        }
        this.itemArray.push(obj)
      },
      //删除属性
      handleRemoveAttr(row) {
        const index = this.itemArray.findIndex(
          item => item => item.code !== row.code
        )
        if (index > -1) {
          let item = this.itemArray[index]
          //清空form字段对应值
          for (var i in item.inputArray) {
            let filed = item.inputArray[i]
            this.form[filed.name] = null
          }
          //清空文件
          this.form.uploadImage = this.form.uploadImage.filter(i => i.typeCode != item.code);
          this.$delete(this.itemArray, index)
          this.tableKey++
        }

      },
      submitForm() {
        this.submitLoading = true
        this.$refs["form"].validate(valid => {
          if (valid) {
            const formData = new FormData()
            if (!isEmpty(this.form.id)) {
              formData.append('id', this.form.id)
            }
            for (var i in this.form.tag) {
              formData.append('tag[' + i + ']', this.form.tag[i])
            }
            formData.append('word', this.form.word)
            if (!isEmpty(this.form.complexNumber)) {
              formData.append('complexNumber', this.form.complexNumber)
            }

            if (!isEmpty(this.form.adjectiveComparative)) {
              formData.append('adjectiveComparative', this.form.adjectiveComparative)
            }

            if (!isEmpty(this.form.adjectiveSuperlative)) {
              formData.append('adjectiveSuperlative', this.form.adjectiveSuperlative)
            }

            if (!isEmpty(this.form.adverbComparative)) {
              formData.append('adverbComparative', this.form.adverbComparative)
            }

            if (!isEmpty(this.form.adverbSuperlative)) {
              formData.append('adverbSuperlative', this.form.adverbSuperlative)
            }

            if (!isEmpty(this.form.pastParticiple)) {
              formData.append('pastParticiple', this.form.pastParticiple)
            }

            if (!isEmpty(this.form.presentParticiple)) {
              formData.append('presentParticiple', this.form.presentParticiple)
            }

            if (!isEmpty(this.form.thirdPersonSingular)) {
              formData.append('thirdPersonSingular', this.form.thirdPersonSingular)
            }

            if (!isEmpty(this.form.nominative)) {
              formData.append('nominative', this.form.nominative)
            }

            if (!isEmpty(this.form.accusative)) {
              formData.append('accusative', this.form.accusative)
            }

            if (!isEmpty(this.form.cardinalNumber)) {
              formData.append('cardinalNumber', this.form.cardinalNumber)
            }

            if (!isEmpty(this.form.ordinalNumber)) {
              formData.append('ordinalNumber', this.form.ordinalNumber)
            }
            // itemArray speechList
            for (var i in this.itemArray) {
              formData.append('speechList[' + i + '].code', this.itemArray[i].code)
              formData.append('speechList[' + i + '].text', this.itemArray[i].text)
            }
            //图片
            for (var i in this.form.uploadImage) {
              let file = this.form.uploadImage[i]
              if (!isEmpty(file.id)) {
                formData.append('uploadWordFileParams[' + i + '].id', file.id)
              } else {
                formData.append('uploadWordFileParams[' + i + '].file', file.raw)
                if (file.url?.startsWith('blob:')) {
                  URL.revokeObjectURL(file.url)
                }
              }
              formData.append('uploadWordFileParams[' + i + '].extendKey', file.typeCode)
            }
            //音频文件
            for (var i in this.form.audioFileList) {
              let file = this.form.audioFileList[i]
              if (!isEmpty(file.id)) {
                formData.append('audioFileList[' + i + '].id', file.id)
              } else {
                formData.append('audioFileList[' + i + '].file', file.raw)
                if (file.url?.startsWith('blob:')) {
                  URL.revokeObjectURL(file.url)
                }
              }
            }
            //form-data 数据构造
            allSaveWords(formData).then(response => {

              this.$modal.msgSuccess("配置单词词性成功")

              this.visible = false
              this.$emit('refreshDataList')
            }).catch((e) => {

            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            this.submitLoading = false
          }
        })
      }
    }
  };
</script>
<style scoped>
  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .item {
    margin-bottom: 18px;
  }

  .text {
    font-size: 14px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  /* 覆盖卡片容器样式 */
  /deep/ .el-upload-list--picture-card .el-upload-list__item,
  /deep/ .el-upload--picture-card {
    width: 180px;
    /* 原默认 148px，缩小一半 */
    height: 180pxpx;
    /* 原默认 148px，缩小一半 */
    line-height: 179px;
    /* 保持垂直居中 */
  }

  /* 调整内部图片尺寸 */
  /deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail {
    width: 100%;
    height: 100%;
    object-fit: cover;
    /* 防止图片变形 */
  }

  /* 调整图标大小（可选） */
  /deep/ .el-icon-plus {
    font-size: 20px;
    /* 原默认 28px，适当缩小 */
  }
</style>
